//
//  DetailViewController.m
//  FinAppsParty App
//
//  Created by Ivan Paquico on 11/11/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "DetailViewController.h"

@interface DetailViewController ()
@property (strong, nonatomic) UIPopoverController *masterPopoverController;
- (void)configureView;
@end

@implementation DetailViewController

@synthesize mapView = _mapView;
@synthesize detailItem = _detailItem;
@synthesize detailDescriptionLabel = _detailDescriptionLabel;
@synthesize masterPopoverController = _masterPopoverController;
@synthesize currentAddress;
@synthesize currentCity;
@synthesize currentCountry;
@synthesize currentComunidad;
@synthesize codigoPostal;
@synthesize geoloc;
@synthesize dormitorios_dobles;
@synthesize dormitorios_individuales;
@synthesize geo;
@synthesize Mainview;
@synthesize pickerView;
@synthesize pickerData;
@synthesize pickerData2;
@synthesize pickerData3;
@synthesize pickerData4;
@synthesize picture1;
@synthesize selector;
@synthesize picture2;
@synthesize picture3;
@synthesize viewOcupation;


- (void)dealloc
{
    [viewOcupation release];
    [picture3 release];
    [picture2 release];
    [_detailItem release];
    [_detailDescriptionLabel release];
    [_masterPopoverController release];
    [_mapView release];
    [currentAddress release];
    [selector release];
    [geo release];
    [Mainview release];
    [pickerView release];
    [pickerData release];
    [pickerData release];
    [pickerData2 release];
    [pickerData3 release];
    [pickerData4 release];
    [picture1 release];
    [dormitorios_dobles release];
    [dormitorios_individuales release];
    [super dealloc];
}

#pragma mark - Managing the detail item

- (void)setDetailItem:(id)newDetailItem
{
    if (_detailItem != newDetailItem) {
        [_detailItem release]; 
        _detailItem = [newDetailItem retain]; 

        // Update the view.
        [self configureView];
    }

    if (self.masterPopoverController != nil) {
        [self.masterPopoverController dismissPopoverAnimated:YES];
    }        
}

- (void)configureView
{
    // Update the user interface for the detail item.

    if (self.detailItem) {
        self.detailDescriptionLabel.text = [self.detailItem description];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    [self configureView];
    
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 100 m
    
    [locationManager startUpdatingLocation];
    
    
    _mapView.delegate = self;
    _mapView.showsUserLocation=TRUE;
    
    CLLocationCoordinate2D location=_mapView.userLocation.coordinate;
    location.latitude=40.814849;
    location.longitude=-73.622732;
  
    geoloc = TRUE;
    
    //self.view.frame = CGRectMake(0, 50, 768, 1500);
    Mainview.frame = CGRectMake(0, 0, 768, 3500);
    
    pickerData = [[NSArray alloc] initWithObjects:@"Enyesado", @"Falso Techo", @"Otros", nil];
    pickerData3 = [[NSArray alloc] initWithObjects:@"Gres", @"Marmol", @"Hidráulico", @"Parquet", @"Otros", nil];
    pickerData2 = [[NSArray alloc] initWithObjects:@"Enyesado", @"Falso Techo", @"Otros", nil];
    pickerData4 = [[NSArray alloc] initWithObjects:@"Aluminio", @"PVC", @"Madera",@"Otros", nil];
    
    imagePickerController = [[UIImagePickerController alloc] init];
	imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    
    
    selector = @"0";
    
    self.title = @"Características";
    
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
                                                                    style:UIBarButtonSystemItemDone target:nil action:nil];
  
  /*  
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera; 
        
    }else{
        
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
*/
    
}

-(void)changePage:(int)numPage{
    NSLog(@"llamado! %d", numPage);
    
    [self becomeFirstResponder];
    
    [UIView beginAnimations:@"MovingUP" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationDelegate:self];
    
    if (numPage == 1) {
        self.Mainview.frame = CGRectMake(0, 0, 768, 3500);
    }if (numPage == 2) {
        self.Mainview.frame = CGRectMake(0, -750, 768, 3500);
          NSLog(@"llamado!!!!! %d", numPage);
    }if (numPage == 3) {
        self.Mainview.frame = CGRectMake(0, -1500, 768, 3500);
        NSLog(@"llamado!!!!! %d", numPage);
    }
     //Mainview.frame = CGRectMake(0, -500, 768, 1500);
    
    pickerView = [[UIPickerView alloc] init];
    
    [UIView commitAnimations];
}

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView { // This method needs to be used. It asks how many columns will be used in the UIPickerView
	return 1; // We only need one column so we will return 1.
    
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component { // This method also needs to be used. This asks how many rows the UIPickerView will have.
	return [pickerData count]; // We will set a new row for every string used in the array.
    
    if (thePickerView.tag == 0) {
        return [pickerData count];
    }if (thePickerView.tag == 1) {
        return [pickerData2 count];
    }if (thePickerView.tag == 2) {
        return [pickerData3 count];
    }if (thePickerView.tag == 3) {
        return [pickerData4 count];
    }
   return [pickerData count];
}

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { // This method asks for what the title or label of each row will be.
    if (thePickerView.tag == 0) {
        return [pickerData objectAtIndex:row];
    }if (thePickerView.tag == 1) {
        return [pickerData2 objectAtIndex:row];
    }if (thePickerView.tag == 2) {
        return [pickerData3 objectAtIndex:row];
    }if (thePickerView.tag == 3) {
        return [pickerData4 objectAtIndex:row];
    }
  
	 // We will set a new row for every string used in the array.
    return [pickerData objectAtIndex:row];
}
/*
-(IBAction)pickImage:(id) sender{
     imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //[self presentModalViewController:imagePickerController animated:YES];
    [self.pop
}*/

-(IBAction)TakeImage:(UIButton *) sender{
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    if (sender.tag == 0) {
        selector = @"0";
    }if (sender.tag == 1) {
        selector = @"1";
    }if (sender.tag == 2) {
        selector = @"2";
    }
    
    [self presentModalViewController:imagePickerController animated:YES];
}

-(IBAction)FinalSlide:(UIButton *) sender{

    ViewOcupation *ocupation = [[ViewOcupation alloc] initWithNibName:@"ViewOcupation" bundle:nil];
    
    ocupation._insideImage1 = self.picture1.image;
    ocupation._insideImage2 = self.picture2.image;
    ocupation._insideImage3 = self.picture3.image;
    
    ocupation.num_dormitorios_dobles = self.dormitorios_dobles.text;
    ocupation.num_dormitorios= self.dormitorios_individuales.text;
  
    
    ocupation.calle = self.currentAddress.text;
    ocupation.pais = self.currentCity.text;
    
    viewOcupation = ocupation;
    
    [self presentModalViewController:viewOcupation animated:NO];
    
    
    ocupation = nil;
    [ocupation release];

   // [self presentModalViewController:self.viewOcupation animated:<#(BOOL)#>
    
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    
    
	[imagePickerController dismissModalViewControllerAnimated:YES];
    if ([selector isEqualToString:@"0"]) {
        self.picture1.image = [info valueForKey:UIImagePickerControllerEditedImage];
   NSLog(@"picture 0!");
    }if ([selector isEqualToString:@"1"]) {
        self.picture2.image = [info valueForKey:UIImagePickerControllerEditedImage];
           NSLog(@"picture 1!");
    }if ([selector isEqualToString:@"2"]) {
        NSLog(@"picture 2!");
        self.picture3.image = [info valueForKey:UIImagePickerControllerEditedImage];
        
    }
       
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	
    [imagePickerController.parentViewController dismissModalViewControllerAnimated:YES];
}

-(IBAction)switchToTwo:(UIButton *)sender{
    
    self.title = @"Sala de estar";

    
    [UIView beginAnimations:@"MovingUP" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationDelegate:self];
    
    self.Mainview.frame = CGRectMake(0, -700, 768, 4500);

    [UIView commitAnimations];

}

-(IBAction)switchToThree:(UIButton *)sender{
    
    self.title = @"Baño y aseo";
    
    [UIView beginAnimations:@"MovingUP" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationDelegate:self];
    
    self.Mainview.frame = CGRectMake(0, -1400, 768, 4500);
    
    [UIView commitAnimations];
    
}

-(IBAction)switchToFour:(UIButton *)sender{
    
      self.title = @"Dormitorios";
    
    [UIView beginAnimations:@"MovingUP" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationDelegate:self];
    
    self.Mainview.frame = CGRectMake(0, -2100, 768, 4500);
    
    [UIView commitAnimations];
    
}

-(IBAction)switchToFive:(UIButton *)sender{
    
      self.title = @"Tipo de Hipoteca";
    
    [UIView beginAnimations:@"MovingUP" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationDelegate:self];
    
    self.Mainview.frame = CGRectMake(0, -2800, 768, 4500);
    
    [UIView commitAnimations];
    
}

-(IBAction)switchValueChanged:(UISwitch *)sender{
    
    if (sender.on) {
 
        geoloc = TRUE;
    }else{
        
        geoloc = FALSE;
        
    }
}


- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    
    //NSLog(@"Coordinates are: %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
    
    
    CLLocationCoordinate2D zoomLocation;
    
    zoomLocation.latitude = newLocation.coordinate.latitude;
    zoomLocation.longitude = newLocation.coordinate.longitude;
    
    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.25*METERS_PER_MILE, 0.25*METERS_PER_MILE);
    
    MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:viewRegion];  
    
       
    [_mapView setRegion:adjustedRegion animated:YES];
    
    // this creates a MKReverseGeocoder to find a placemark using the found coordinates
    MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
    geoCoder.delegate = self;
    [geoCoder start];

    /*
    MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc] initWithTitle:@"Your Position" andCoordinate:zoomLocation];
        
	[self.mapView addAnnotation:newAnnotation];
    */
    
}

// this delegate method is called if an error occurs in locating your current location
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 
{
   // NSLog(@"locationManager:%@ didFailWithError:%@", manager, error);
}

// this delegate is called when the reverseGeocoder finds a placemark
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
    MKPlacemark * myPlacemark = placemark;
    // with the placemark you can now retrieve the city name
   // NSString *city = [myPlacemark.addressDictionary objectForKey:(NSString*) kABPersonAddressCityKey];
   // NSLog(@"myPlacemark %@", myPlacemark);
    if (geoloc) {
        
        currentAddress.text = [NSString stringWithFormat:@"%@", [[myPlacemark.addressDictionary objectForKey:@"FormattedAddressLines"] objectAtIndex:0]] ;
        currentCity.text = [NSString stringWithFormat:@"%@", [myPlacemark.addressDictionary objectForKey:@"City"]] ;
        currentCountry.text = [NSString stringWithFormat:@"%@", [myPlacemark.addressDictionary objectForKey:@"Country"]] ;
        currentComunidad.text = [NSString stringWithFormat:@"%@", [myPlacemark.addressDictionary objectForKey:@"State"]] ;
        codigoPostal.text = [NSString stringWithFormat:@"%@", [myPlacemark.addressDictionary objectForKey:@"ZIP"]] ;
        
    }
   
   // NSLog(@"%@", myPlacemark.addressDictionary);
}

-(IBAction) textFieldAdressEditing : (id) sender{
    if (geoloc) {
        [sender resignFirstResponder];
    }
    NSLog(@"adress!!");
}

-(IBAction) textFieldEndEditing : (id) sender{

        [sender resignFirstResponder];
    
    NSLog(@"Aqui habra que guardar todos los datos!!!!!");
    
    [self changePage:2];
}

-(IBAction) textFieldCityEditing : (id) sender{
    if (geoloc) {
        [sender resignFirstResponder];
    }
     //NSLog(@"city!!");
}
-(IBAction) textFieldCountryEditing : (id) sender{
    if (geoloc) {
        [sender resignFirstResponder];
    }
   // NSLog(@"textFieldCountryEditing!!");
}
-(IBAction) textFieldComunidadEditing : (id) sender{
    if (geoloc) {
        [sender resignFirstResponder];
    }
    //NSLog(@"textFieldComunidadEditing!!");
}
-(IBAction) textFieldPostalEditing : (id) sender{
    if (geoloc) {
        [sender resignFirstResponder];
    }
   // NSLog(@"textFieldPostalEditing!!");
}


// this delegate is called when the reversegeocoder fails to find a placemark
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
    NSLog(@"reverseGeocoder:%@ didFailWithError:%@", geocoder, error);
}



- (void)viewDidUnload
{
    [self setMapView:nil];
   // [self set_adress:nil];
    [self setDormitorios_dobles:nil];
    [self setDormitorios_individuales:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    /*
    // Return YES for supported orientations
    if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
        return YES;
    } else if(interfaceOrientation == UIInterfaceOrientationLandscapeRight){
        return YES;
    }
    else return NO;*/
    
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft);

    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Detail", @"Detail");
    }
    return self;
}
							
#pragma mark - Split view

- (void)splitViewController:(UISplitViewController *)splitController willHideViewController:(UIViewController *)viewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)popoverController
{
    barButtonItem.title = NSLocalizedString(@"Master", @"Master");
    [self.navigationItem setLeftBarButtonItem:barButtonItem animated:YES];
    self.masterPopoverController = popoverController;
}

- (void)splitViewController:(UISplitViewController *)splitController willShowViewController:(UIViewController *)viewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
    // Called when the view is shown again in the split view, invalidating the button and popover controller.
    [self.navigationItem setLeftBarButtonItem:nil animated:YES];
    self.masterPopoverController = nil;
}

@end
